package com.manolo.framework.connection.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Set;

import com.google.gson.Gson;
import com.manolo.framework.connection.entity.Player;

/**
 * 
 */

/**
 * @author gustavo
 * 
 */
public class ServerPlayerLister implements Runnable {

	private Integer playerId;

	private HashMap<Integer, Player> players;

	private Socket socket;

	private BufferedReader in;

	public ServerPlayerLister(Integer id, Socket socket,
			HashMap<Integer, Player> message) {

		playerId = id;
		players = message;
		players.get(playerId).setId(playerId);

		try {
			this.socket = socket;
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void receive() throws IOException {
		String msg = in.readLine();
		if (msg == null) {
			System.out.println("client out");
			resetConnection();
		} else {
			System.out.println("client send" + msg);
			if (msg != null && msg.trim().length() > 6) {
				// TODO Write method JSON

				Gson gson = new Gson();
				Player obj2 = gson.fromJson(msg, Player.class);
				// Message msgt = new Message(playerId, msg);

				Set<Integer> keys = players.keySet();
				for (Integer id : keys) {
					if (id == playerId) {
						// TODO refectory this code
						players.get(id).getCards().clear();
						players.get(id).getCards().addAll(obj2.getCards());
					} else {
						players.get(id).getMessages().clear();
						players.get(id).getMessages()
								.addAll(obj2.getMessages());
					}
				}
			}
		}
	}

	private void resetConnection() throws IOException {
		socket.close();
	}

	@Override
	public void run() {
		while (true) {
			try {
				if(socket.isClosed()){
					synchronized (this.players.get(playerId)) {
						this.players.get(playerId).notifyAll();
					}	
					
					break;
					
				}
				receive();
				synchronized (this.players.get(playerId)) {
					this.players.get(playerId).notifyAll();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
